package ink.carnation.imtalk.service.impl;

import ink.carnation.imtalk.service.EmailService;
import ink.carnation.imtalk.util.EmailUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @author: flbu920
 * @date 2020/9/24
 */
@Service
public class EmailServiceImpl implements EmailService {
    @Autowired
    private JavaMailSender mailSender;
    @Autowired
    private RedisTemplate redisTemplate;
    @Value("${spring.mail.username}")
    private String emailFrom;
    @Resource
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;

    @Override
    @Async
    public String sendEmail(String emailAddress) {
        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        simpleMailMessage.setSubject("IM-Talk邮箱验证");
        simpleMailMessage.setFrom(emailFrom);
        simpleMailMessage.setTo(emailAddress);
        String message = EmailUtil.generateCode();
        simpleMailMessage.setText("Hello,这是您的IMTalk邮箱验证码: " + message + "\n" +
                "请您在三分钟内进行验证，如果不是您在操作，请忽略");
        //使用线程池发送邮件
        threadPoolTaskExecutor.execute(()->{mailSender.send(simpleMailMessage);});
        //存入Redis，key是email，value是验证码，过期时间为3分钟
        redisTemplate.boundValueOps("IMTalkEmail:" + emailAddress).set(message, 300, TimeUnit.SECONDS);
        return message;
    }

    @Override
    public Boolean verification(String email, String message) {
        String verityMessage = (String) redisTemplate.boundValueOps("IMTalkEmail:" + email).get();
        if (verityMessage != null && message.equals(verityMessage)) {
            //清除缓存数据
            redisTemplate.delete("IMTalkEmail:" + email);
            return true;
        }
        return false;
    }
}
